/**
 * base64 下载
 */
export function downloadFileBase64(fileName: string, base64: string) {
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = base64
    document.body.appendChild(elink)
    elink.click()
    document.body.removeChild(elink)
  }
}

export const fileCanDownload = async (data: Blob) => {
  if (data.size > 2000) return true
  const txt = await data.text()
  let obj: any = {}
  try {
    obj = JSON.parse(txt)
  } catch (e) {
    console.error(e)
  }
  if (obj.code) {
    console.error(obj.msg || '下载文件失败')
    return false
  }
  return true
}
/**
 * blob 下载
 */
export async function downloadFile(fileName: string, resBlob: Blob) {
  const canDownload = await fileCanDownload(resBlob)
  if (!canDownload) return
  const blob = new Blob([resBlob])
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  }
}

function getMidNum(str: any, start: any, len: any) {
  if (start + len > 0) {
    return +str.substr(start < 0 ? 0 : start, start < 0 ? start + len : len)
  } else {
    return 0
  }
}
/**
 * 大数据比较大小,支持千分位数字
 * a<b返回 -1
 * a==b 返回 0
 * a>b 返回 1
 */
export const bigNumCompare = (_a: string | number, _b: string | number) => {
  const a = _a + ''
  const b = _b + ''
  let back = 0
  const max = Math.ceil(Math.max(a.length, b.length) / 15)
  //分成多少段,从左边开始
  for (let i = max; i > 0; i--) {
    const num1 = getMidNum(a, a.length - i * 15, 15)
    const num2 = getMidNum(b, b.length - i * 15, 15)
    //15位数字相减
    const cur = num1 - num2
    if (cur < 0) {
      back = -1
      break
    } else if (cur > 0) {
      back = 1
      break
    }
  }
  return back
}

/**
 * JSON导出excel
 * @params {
 *  data:Array 原数据
 *  FileName:string 导出的文件名,默认为时间戳
 *  titleMapping:Array [{
 *      title:string 列名,
 *      sort:number 排序,
 *      field:string 对应字段
 *    }],
 *  tableName:string 工作表名称
 * }
 */
export const exportExcel = (params: any) => {
  const { data, FileName = Date.now(), titleMapping, tableName = 'Sheet1' } = params
  if (!data) return
  let JSONData: any = data
  let title: any = []
  if (titleMapping?.length) {
    const sortData = titleMapping.sort((a: number, b: number) => a - b)
    JSONData = JSONData.map((ele: any) => {
      const obj: any = {}
      sortData.forEach((item: any) => {
        obj[item.field] = ele[item.field]
      })
      return obj
    })
    title = titleMapping.map((ele: any) => ele.title)
  } else {
    title = Object.keys(data[0])
    JSONData = JSONData.map((ele: any) => {
      const obj: any = {}
      title.forEach((item: any) => {
        obj[item] = ele[item]
      })
      return obj
    })
  }
  const arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData
  let excel = '<table>'
  let row = '<tr>'
  if (title) {
    for (const i in title) {
      row += '<th align=\'center\'>' + title[i] + '</th>'
    }
  } else {
    for (const i in arrData[0]) {
      row += '<th align=\'center\'>' + i + '</th>'
    }
  }
  excel += row + '</tr>'
  for (let i = 0; i < arrData.length; i++) {
    let row = '<tr>'
    for (const index in arrData[i]) {
      const value = arrData[i][index] == null ? '' : arrData[i][index]
      row += '<td align=\'center\'>' + value + '</td>'
    }
    excel += row + '</tr>'
  }
  excel += '</table>'
  let excelFile =
    '<html xmlns:o=\'urn:schemas-microsoft-com:office:office\' xmlns:x=\'urn:schemas-microsoft-com:office:excel\' xmlns=\'http://www.w3.org/TR/REC-html40\'>'
  excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">'
  excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel'
  excelFile += '; charset=UTF-8">'
  excelFile += '<head>'
  excelFile += '<!--[if gte mso 9]>'
  excelFile += '<xml>'
  excelFile += '<x:ExcelWorkbook>'
  excelFile += '<x:ExcelWorksheets>'
  excelFile += '<x:ExcelWorksheet>'
  excelFile += '<x:Name>'
  excelFile += `{${tableName}}`
  excelFile += '</x:Name>'
  excelFile += '<x:WorksheetOptions>'
  excelFile += '<x:DisplayGridlines/>'
  excelFile += '</x:WorksheetOptions>'
  excelFile += '</x:ExcelWorksheet>'
  excelFile += '</x:ExcelWorksheets>'
  excelFile += '</x:ExcelWorkbook>'
  excelFile += '</xml>'
  excelFile += '<![endif]-->'
  excelFile += '</head>'
  excelFile += '<body>'
  excelFile += excel
  excelFile += '</body>'
  excelFile += '</html>'
  const uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile)
  const link = document.createElement('a')
  link.href = uri
  link.style.visibility = 'hidden'
  link.download = FileName + '.xls'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
